const express = require('express');
const user = express.Router() //创建路由
const fs = require("fs")
const { User } = require("../../mod/user")
const { Code } = require("../../mod/code")
const multer = require("multer")
const { getCode } = require("../../tool/func")

const Mail = require("../../tool/mail.js")
const { setToken } = require('../../token/constant')

const { Jurisdiction } = require("../../mod/jurisdiction")
const {
  setCrypto
} = require('../../tool/crypto.js')


let { adminRouter,
  handleJur,
  teacherRouter,
  studentRouter } = require("../../tool/tool")


// 新建一个仓库
var storage = multer.diskStorage({
  //设置上传后的文件路径
  destination: function (req, file, cb) {
    cb(null, './public/userheader/')
  },
  //给上传文件重命名，以防命名重复
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}+${file.originalname}`)
  }
})

// 配置一个接收器，用于使用仓库
var upload = multer({
  storage: storage
})

// 更换头像
user.post("/updataUserHeader", upload.single("headerurl"), async (req, res) => {
  //user_id 
  let { _id } = req.body
  let headerUrl = 'userheader/' + req.file.filename   //单文件上传  req.file  ;  多文件上传  req.files

  // 表示上传成功，删除原来的 
  let userdata = await User.findOne({ _id })
  if (userdata == null) {
    return res.json({
      code: 401,
      msg: "用户信息有误",
    })
  }
  let oldurl = userdata.headerUrl
  if (oldurl == "userheader/default.png") { // 表示原来使用的默认头像
    let data1 = await User.updateOne({ _id }, { headerUrl })
    let data = await User.findOne({ _id })
    if (data == null) {
      return res.json({
        code: 501,
        msg: "更新头像失败",
      })
    }
    return res.json({
      code: 200,
      msg: "更新头像成功",
      data
    })
  } else {
    // 需要先删除原来的
    let oldurl1 = global.initUrl + `/public/${oldurl}`

    // 这儿的路径必须使用绝对路径
    fs.unlink(oldurl1, async (err) => {
      if (err) {
        console.log(err)
        console.log('old文件删除失败')

        // 需要去删除新上传的图片
        fs.unlink(global.initUrl + `/public/${headerUrl}`, async (err) => {
          console.log("kkk")
          if(err){
            return {
              code: 502,
              msg: "原头像删除失败,新头像删除失败",
            }
          }else{
            console.log("lll")
            return {
              code: 502,
              msg: "原头像删除失败,新头像已被删除",
            }
          }
        })
      
      }
      
      let data1 = await User.updateOne({ _id }, { headerUrl })
      let data = await User.findOne({ _id })

      if (data == null) {
        return res.json({
          code: 501,
          msg: "更新头像失败",
          
        })
      }
      return res.json({
        code: 200,
        msg: "更新头像成功",
        data
      })
    })

  }
})

// admin用户直接注册新用户
user.post("/adminRegisterUser", async (req, res) => {
  // admin_id
  // email password shengfen xuehao
  let { admin_id, email, password, shengfen, xuehao } = req.body

  // 先验证是不是admin
  let adminData = await User.findOne({ _id: admin_id })
  if (adminData == null) {
    return res.json({
      code: 401,
      msg: "非法添加新用户"
    })
  }

  // 查看用户是否已经存在
  let userdata = await User.findOne({ email })
  if (userdata != null) {
    return res.json({
      code: 401,
      msg: "该用户已经存在"
    })
  }

  let userdata1 = await User.findOne({ xuehao })
  if (userdata1 != null) {
    return res.json({
      code: 401,
      msg: "该用户已经存在"
    })
  }

  password = setCrypto(password)
  // 查找admin的对应路由列表
  let routerdata = await Jurisdiction.findOne({ user_grade: shengfen })

  let data = await new User({
    email,
    password,
    shengfen,
    xuehao,
    user_jurisdiction_routerlist: routerdata.jurisdiction_routerlist
  }).save()

  res.json({
    code: 200,
    msg: "添加新用户成功",
    data
  })


})

// admin 用户获取所有注册用户
user.get("/getusers", async (req, res) => {
  // 需要参数 用户id 第几页 每页多少条 
  let { num = 1, pageSize = 5 } = req.query
  skip = (pageSize - 0) * (num - 1)    //跳过多少条，
  let total = await User.find().countDocuments()
  let data = await User.find({}).skip(skip).limit(pageSize - 0)

  res.json({
    code: 200,
    msg: "获取成功",
    total,
    data
  })
})

// admin 用户更新用户信息
user.post("/updataUserData", async (req, res) => {
  // 用户提交的信息
  let { password1, _id, shengfen1, shengfen } = req.body
  // 先对身份信息进行修改
  if (shengfen1 == "学生") {
    shengfen1 = 0;
  } else if (shengfen1 == "老师") {
    shengfen1 = 1;
  } else if (shengfen1 == "管理员") {
    shengfen1 = 2;
  }

  // 先查看身份是否被修改
  if (shengfen != shengfen1) {  // 身份被修改
    req.body.shengfen = shengfen1  //  shengfen1 是新身份
    // 获取新身份的路由

    let data = await Jurisdiction.findOne({ user_grade: req.body.shengfen })
    // console.log(data.jurisdiction_routerlist)
    req.body.user_jurisdiction_routerlist = data.jurisdiction_routerlist
  }
  req.body.shengfen = shengfen1
  if (password1) {  // 表示修改了密码
    // 对新密码进行加密
    req.body.password = setCrypto(password1)

    let data = await User.updateOne({ _id }, req.body)

    return res.json({
      code: 200,
      msg: "修改密码成功"
    })
  }

  let data = await User.updateOne({ _id }, req.body)
  // console.log(data)
  // 没有修改密码
  return res.json({
    code: 200,
    msg: "修改用户信息成功"
  })

})

// admin 用户修改具体的用户的相关权限
user.post("/updataUserJur", async (req, res) => {
  // admin_id  必须是管理员才可以获取
  // user_id  要被修改的用户id
  // arr  提交的新的权限id列表
  let { admin_id, user_id, arr } = req.body
  let data = await User.findOne({ _id: admin_id, shengfen: 2 })

  if (data == null) {
    return res.json({
      code: 201,
      message: "你没有权限提交"
    })
  }
  // 根据传递过来的新的路由权限数组，重新转化为 路由数组保存
  let jurisdiction_routerlist = handleJur(arr)
  // console.log(jurisdiction_routerlist)

  await User.updateOne({ _id: user_id }, { user_jurisdiction_routerlist: jurisdiction_routerlist })

  return res.json({
    code: 200,
    msg: "设置该用户权限成功",
  })
})

// admin 用户修改老师及学生的相关权限
user.post("/updataClassJur", async (req, res) => {
  // user_id  必须是管理员才可以获取
  // shengfen 0 / 1  修改的是 老师还是学生权限
  // arr  提交的新的权限id列表
  let { _id, shengfen, arr } = req.body
  let data = await User.findOne({ _id, shengfen: 2 })

  if (data == null) {
    return res.json({
      code: 201,
      message: "你没有权限获取"
    })
  }
  // 根据传递过来的新的路由权限数组，重新转化为 路由数组保存
  let jurisdiction_routerlist = handleJur(arr)
  // console.log(jurisdiction_routerlist)
  if (shengfen == 0) {  // 修改学生的权限

    let routerStudent = await Jurisdiction.updateMany({ user_grade: 0 }, { jurisdiction_routerlist })
    let routerStudent1 = await User.updateMany({ shengfen: 0 }, { user_jurisdiction_routerlist: jurisdiction_routerlist })

    return res.json({
      code: 200,
      msg: "设置学生权限成功",
    })
  }

  if (shengfen == 1) {  // 修改老师的权限
    let routerTeacher = await Jurisdiction.updateMany({ user_grade: 1 }, { jurisdiction_routerlist })
    let routerStudent1 = await User.updateMany({ shengfen: 1 }, { user_jurisdiction_routerlist: jurisdiction_routerlist })

    res.json({
      code: 200,
      msg: "设置老师权限成功",
    })
  }


})

// 获取老师及学生的相关权限
user.get("/getClassJur", async (req, res) => {
  // user_id  必须是管理员才可以获取
  // shengfen 0 / 1
  let { _id, shengfen } = req.query
  let data = await User.findOne({ _id, shengfen: 2 })

  if (data == null) {
    return res.json({
      code: 201,
      message: "你没有权限获取"
    })
  }

  if (shengfen == 0) {  // 获取学生的权限
    let routerStudent = await Jurisdiction.findOne({ user_grade: 0 })
    return res.json({
      code: 200,
      msg: "获取学生权限成功",
      data: routerStudent.jurisdiction_routerlist
    })
  }

  if (shengfen == 1) {
    let routerTeacher = await Jurisdiction.findOne({ user_grade: 1 })
    res.json({
      code: 200,
      msg: "获取老师权限成功",
      data: routerTeacher.jurisdiction_routerlist
    })
  }


})

// 发送邮箱验证码
user.get("/postmail", async (req, res) => {
  let {
    email
  } = req.query

  // 验证是否是合法邮箱
  var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  if (!reg.test(email)) {
    return res.json({
      code: 202,
      msg: "邮箱不合法"
    })
  }


  let time = Date.now()
  // 查看5分钟内，该email是否发送过验证码
  let data2 = await Code.findOne({ email })
  if (data2 != null) {  // 以前发送过
    // 5分钟内不允许重复发送
    if (time - data2.send_time < 60 * 5 * 1000) {
      return res.json({
        code: 201,
        msg: "5分钟内只能发送一次"
      })
    }
    // 
    let codetime = getCode()  // 产生验证码
    let data = await Mail.sendmail(email, codetime)
    if (data) {
      // 将发送验证码的信息更新
      let data1 = await Code.updateOne({ email }, { code_val: codetime, send_time: time })
      if (data1 !== null) {
        return res.json({
          code: 200,
          msg: "发送成功"
        })
      }
      return res.json({
        code: 201,
        msg: "发送失败,请重新获取"
      })
    } else {
      return res.json({
        code: 201,
        msg: "发送失败,请重新获取"
      })
    }

  } else {
    // 第一次发送验证码
    let codetime = getCode()  // 产生验证码
    let data = await Mail.sendmail(email, codetime)
    if (data) {
      // 将发送验证码的信息保存
      let data1 = await new Code({ email, code_val: codetime, send_time: time }).save()
      if (data1 !== null) {
        return res.json({
          code: 200,
          msg: "发送成功"
        })
      }
      return res.json({
        code: 201,
        msg: "发送失败,请重新获取"
      })
    } else {
      return res.json({
        code: 201,
        msg: "发送失败,请重新获取"
      })
    }

  }

})


// 登陆用户
user.get("/login", async (req, res) => {
  let { password, xuehao } = req.query
  password = setCrypto(password)

  let data = await User.findOne({ password, xuehao })
  if (data == null) {
    return res.json({
      msg: "密码或学号错误",
      code: "401",
    })
  }
  //设置token
  let token = "Bearer " + setToken(req.query.xuehao)     //将用户的xuehao作为token的一部分,可以换
  res.json({
    msg: "登录成功",
    code: "200",
    token: token,
    data
  })

})

// 注册用户
user.post("/register", async (req, res) => {
  let { password, xuehao, email, code_val } = req.body
  // 查看是否发送过验证码
  let data2 = await Code.findOne({ email })
  if (data2 == null) {
    return res.json({
      code: 201,
      msg: "请先发送验证码"
    })
  }
  let newTime = Date.now()
  // 验证码超时
  if (newTime - data2.send_time > 60 * 5 * 1000) {
    return res.json({
      code: 202,
      msg: "验证码过期，请重新发送"
    })
  }
  // 验证码不正确
  if (code_val != data2.code_val) {
    return res.json({
      code: 203,
      msg: "验证码不正确，请重新输入"
    })
  }

  let newuser = await User.findOne({
    email
  })


  if (newuser != null) {
    return res.json({
      code: 204,
      msg: "该邮箱已经注册过了"
    })
  }


  let newuser1 = await User.findOne({
    xuehao
  })

  if (newuser1 != null) {
    return res.json({
      code: 204,
      msg: "该学号已经注册过了"
    })
  }



  // 查找对应路由列表,默认注册的是一个学生用户
  let routerdata = await Jurisdiction.findOne({ user_grade: 0 })
  password = setCrypto(password)

  // 删除验证码发送记录
  let data3 = await Code.deleteOne({ email })
  if (data3.n != 1) {
    return res.json({
      code: 200,
      msg: "登陆成功,但验证码等待5分钟后才能重新发送"
    })
  }

  let data = await new User({ password, xuehao, email, user_jurisdiction_routerlist: routerdata.jurisdiction_routerlist }).save()

  res.json({
    msg: "注册新用户成功",
    code: "200",
    data
  })

})

//找回密码
user.post("/getpassword", async (req, res) => {
  //需要参数 邮箱、验证码，两次密码，重设的username
  let {
    email,
    xuehao,
    code_val,
    password,
    checkPass
  } = req.body

  //检查密码是否一致
  if (password != checkPass) {
    return res.json({
      code: 201,
      msg: "密码不一致"
    })
  }

  //对密码加密
  password = setCrypto(password)


  console.log(1)
  //检查该邮箱是否被注册过
  let data = await User.findOne({
    email, xuehao
  })
  console.log(data)
  if (data == null) {
    return res.json({
      code: 202,
      msg: "该用户不存在，请重新检查你的邮箱或学号是否正确"
    })
  }
  console.log(2)
  // 查看是否发送过验证码
  let data2 = await Code.findOne({ email })
  if (data2 == null) {
    return res.json({
      code: 201,
      msg: "请先发送验证码"
    })
  }
  let newTime = Date.now()
  // 验证码超时
  if (newTime - data2.send_time > 60 * 5 * 1000) {
    return res.json({
      code: 202,
      msg: "验证码过期，请重新发送"
    })
  }
  // 验证码不正确
  if (code_val != data2.code_val) {
    return res.json({
      code: 203,
      msg: "验证码不正确，请重新输入"
    })
  }

  console.log("3")
  //验证都通过，开始修改用户密码
  let datalist = await User.updateOne({
    email, xuehao
  }, {
    password
  })

  if (datalist.n != 1) {
    return res.json({
      code: 203,
      msg: "找回密码失败，请重试"
    })
  }

  // 删除验证码发送记录
  let data3 = await Code.deleteOne({ email })
  if (data3.n == 1) {
    return res.json({
      code: 200,
      msg: "修改密码成功，请重新登陆"
    })
  }

  res.json({
    code: 201,
    msg: "修改密码成功，但验证码等待5分钟后才能重新发送"
  })




})

// 用户修改基本信息

module.exports = user